package com.zjr.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import com.zjr.dao.UserDao;
import com.zjr.domain.User;
import com.zjr.utils.Page;
/**
 * 用户DAO实现类
 * */
public class UserDaoImpl extends HibernateDaoSupport implements UserDao{

	@Override
	public User login(User user) {
		String hql = "from User where username=? and password=?";
		List<User> list = (List<User>) this.getHibernateTemplate().find(hql, user.getUsername(), user.getPassword());
		if(list.size() > 0){
			return list.get(0);
		}
		return null;
	}

	@Override
	public boolean save(User user) {
		Serializable result = this.getHibernateTemplate().save(user);
		return (Integer)result > 0;
	}

	@Override
	public List<User> findAll() {
		String hql="from User";
		return (List<User>) this.getHibernateTemplate().find(hql);
	}

	@Override
	public User findById(int uid) {
		return this.getHibernateTemplate().get(User.class, uid);
	}

	@Override
	public void modify(User user) {
		this.getHibernateTemplate().update(user);
	}

	@Override
	public void delete(int uid) {
		this.getHibernateTemplate().delete
			(this.getHibernateTemplate().get(User.class, uid));
	}

	@Override
	public List<User> findByDid(int did) {
		String hql = "from User where did = ?";
		if(this.getHibernateTemplate().find(hql, did) != null){
			return (List<User>) this.getHibernateTemplate().find(hql, did);
		}
		return null;
	}

	@Override
	public int count() {
		String hql = "select count(*) from User as user";
		List<Long> list = (List<Long>) this.getHibernateTemplate().find(hql);
		if(list != null && list.size() > 0){
			return list.get(0).intValue();
		}
		
		return 0;
	}
	
	//分页查询用户
	@Override
	public List<User> queryUser(Page page) {
		String hql = "from User";
		List list =  (List) this.getHibernateTemplate().execute(new HibernateCallback() {

			@Override
			public Object doInHibernate(Session session) throws HibernateException {
				List list2 = session.createQuery(hql)
									.setFirstResult(page.getDbIndex())
									.setMaxResults(page.getDbNumber())
									.list();
				return list2;
			}
			
		});
		return list;
	}
	
	public User findByUsername(String username){
		String hql = "from User where username=?";
		List<User> list = (List<User>) this.getHibernateTemplate().find(hql, username);
		return list.get(0);
	}
}
 